package com.ruoyi.map.controller;

import com.cyl.h5.domain.vo.RecentlyBuyCVo;
import com.cyl.h5.domain.vo.RecentlyBuyVo;
import com.cyl.manager.oms.domain.entity.OrderItem;
import com.cyl.manager.pms.domain.entity.Brand;
import com.cyl.manager.pms.domain.entity.PmsBrandAttention;
import com.cyl.manager.pms.domain.query.BrandQuery;
import com.cyl.manager.pms.domain.query.ProductQuery;
import com.cyl.manager.pms.service.BrandService;
import com.cyl.manager.pms.service.PmsBrandAttentionService;
import com.cyl.manager.ums.domain.entity.UserInfo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.map.domain.*;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.map.dto.PmsProductDTO;
import com.ruoyi.map.query.PmsProductQuery;
import com.ruoyi.map.service.IPmsBrandService;
import com.ruoyi.map.service.IPmsHistoryService;
import com.ruoyi.map.service.IPmsProductCategoryService;
import com.ruoyi.map.service.IPmsProductService;
import com.ruoyi.map.service.impl.PmsLabelService;
import com.ruoyi.tokenTools.UserLoginToken;
import com.ruoyi.web.core.config.LocalUserInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author sangsijing
 * @since 2025/5/8 16:16
 * app小程序   商城接口
 */
@Api(tags = "商城模块接口")
@RestController
@RequestMapping("/app/product")
public class AppProductController extends BaseController {


    @Autowired
    private IPmsProductService pmsProductService;

    @Autowired
    private IPmsProductCategoryService pmsProductCategoryService;

    @Autowired
    private IPmsBrandService pmsBrandService;

    @Autowired
    private IPmsHistoryService pmsHistoryService;

    @Autowired
    private PmsLabelService pmsLabelService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private PmsBrandAttentionService brandAttentionService;

    /**
     * 商城首页
     */
    @UserLoginToken
    @ApiOperation("商城首页")
    @GetMapping("/productHome")
    public R<ProductDto> productHome(ProductDto productDto) {
        try {

            //商品分类列表
            List<PmsProductCategory> pmsProductCategoryList = pmsProductCategoryService.getList();
            productDto.setProductCategoryList(pmsProductCategoryList);

            //商品促销列表
            List<PmsProductDTO> promotionList = pmsProductService.promotionList();
            productDto.setPromotionList(promotionList);
            return R.ok(productDto);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("查询商品表列表")
    @PostMapping("/productLists")
    public ResponseEntity<Page<PmsProduct>> productLists(@RequestBody PmsProductQuery query, Pageable page) {
        List<PmsProduct> list = pmsProductService.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }

//    public ResponseEntity<Page<FhMapWeather>> weatherList(@RequestBody FhMapWeather query, Pageable page) {
//        List<FhMapWeather> list = tfhMapWeatherService.selectList(query, page);
//        for (FhMapWeather city : list) {
//            fhMapWeatherService.processCityWeather(city);
//        }
//        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
//    }

    //商品详情
    @ApiOperation("商品详情")
    @GetMapping("/productDetails")
    public R<PmsProductDTO> productDetails(Long id) throws IOException {
        PmsProductDTO pmsProduct = pmsProductService.productDetails(id);
        //根据品牌id获取品牌
        Long brandId = pmsProduct.getBrandId();
        PmsBrand pmsBrand = pmsBrandService.getDetails(brandId);
        pmsProduct.setPmsBrand(pmsBrand);
        return R.ok(pmsProduct);
    }

    /*
    *   智能推荐    （缺少天气和鱼类搜索）
    * */
    @ApiOperation("智能推荐")
    @PostMapping("/getRecommendList")
    public ResponseEntity<PageImpl<PmsProductDTO>> getRecommendList(@RequestBody PmsProductDTO query, Pageable page){
        //切割商品分类id
        if (StringUtils.isNotBlank(query.getCategoryIds())) {
            query.setCategoryIdList(
                    Arrays.stream(query.getCategoryIds().split(","))
                            .map(String::trim)
                            .filter(StringUtils::isNumeric)
                            .collect(Collectors.toList())
            );
        }

        List<PmsProductDTO> recommendList = pmsProductService.getRecommendList(query,page);

        return ResponseEntity.ok(new PageImpl<>(recommendList, page, recommendList.size()));
    }



    /*
     *   搜索历史记录信息
     * */
    @ApiOperation("搜索历史记录信息")
    @GetMapping("/getHistoryList")
    public R<List<PmsHistory>> getHistoryList(PmsHistory pmsProduct){
        //获取当前用户id
        Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
        pmsProduct.setUserId(userId);
        //查询历史记录
        List<PmsHistory> list = pmsHistoryService.getHistoryList(pmsProduct);
        return R.ok(list);
    }



    /*
     *   搜索关键词
     * */
    @ApiOperation("搜索关键词")
    @GetMapping("/getCruxList")
    public R<List<PmsHistory>> getCruxList(PmsHistory pmsProduct){
        //查询所有历史记录
        List<PmsHistory> list = pmsHistoryService.getWord(pmsProduct);
        return R.ok(list);
    }


    //查询标签列表
    @ApiOperation("查询标签列表")
    @GetMapping("/getLabelList")
    public R<List<PmsLabel>> getLabelList(PmsProductQuery query, Pageable page){
        //根据名称查询商品信息
        List<PmsProduct> pmsProducts = pmsProductService.selectList(query, page);
        if (pmsProducts == null || pmsProducts.size() == 0){
            return R.ok(new ArrayList<>(),"未查询到商品信息");
        }
        String labelIds = "";
        for (PmsProduct pmsProduct : pmsProducts) {
            if (!labelIds.isEmpty()) {
                labelIds += ","; // 添加分隔符
            }
            labelIds += pmsProduct.getLabelId();
        }
        Long[] longArray = Arrays.stream(labelIds.split(","))
                .map(String::trim)       // 去除空格
                .filter(s -> !s.isEmpty())         // 过滤掉空字符串
                .map(Long::valueOf)      // 转换为Long
                .toArray(Long[]::new);   // 转为Long数组
        List<PmsLabel> labelList = pmsLabelService.getLabelList(longArray);
        return R.ok(labelList);
    }



    /*
     *   商品搜索
     * */
    @ApiOperation("商品搜索(用于多个搜索条件)")
    @PostMapping("/productSearch")
    public ResponseEntity<PageImpl<PmsProductDTO>> productSearch(@RequestBody PmsProductDTO query, Pageable page){
        //切割商品分类id
        if (StringUtils.isNotBlank(query.getCategoryIds())) {
            query.setCategoryIdList(
                    Arrays.stream(query.getCategoryIds().split(","))
                            .map(String::trim)
                            .filter(StringUtils::isNumeric)
                            .collect(Collectors.toList())
            );
        }
        //切割标签id
        if (StringUtils.isNotBlank(query.getLabelId())) {
            query.setLabelLists(
                    Arrays.stream(query.getLabelId().split(","))
                            .map(String::trim)
                            .filter(StringUtils::isNumeric)
                            .collect(Collectors.toList())
            );
        }
        //切割精选服务
        if (StringUtils.isNotBlank(query.getService())) {
            query.setServiceList(
                    Arrays.stream(query.getService().split(","))
                            .map(String::trim)
                            .collect(Collectors.toList())
            );
        }
        List<PmsProductDTO> list = pmsProductService.productSearch(query,page);

        return ResponseEntity.ok(new PageImpl<>(list, page, list.size()));
    }


    /*
     *   推荐商品
     * */
    @ApiOperation("推荐商品")
    @PostMapping("/recommend")
    public ResponseEntity<PageImpl<PmsProductDTO>> recommend(@RequestBody PmsProductDTO query, Pageable page){
        List<PmsProductDTO> list = pmsProductService.recommend(query,page);

        return ResponseEntity.ok(new PageImpl<>(list, page, list.size()));
    }



    @ApiOperation("品牌列表")
    @PostMapping("/brandList")
    public ResponseEntity<Page<Brand>> brandList(@RequestBody BrandQuery query, Pageable page) {

        List<Brand> list = brandService.selectList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }

    @ApiOperation("品牌商品列表")
    @PostMapping("/brandProductList")
    public ResponseEntity<Page<PmsProductDTO>> brandProductList(@RequestBody PmsProductDTO query, Pageable page) {
        //切割标签id
        if (StringUtils.isNotBlank(query.getLabelId())) {
            query.setLabels(
                    Arrays.stream(query.getLabelId().split(","))
                            .map(String::trim)
                            .collect(Collectors.toList())
            );
        }
        List<PmsProductDTO> list = pmsProductService.brandProductList(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, ((com.github.pagehelper.Page)list).getTotal()));
    }


    @ApiOperation("品牌详情")
    @GetMapping("/brandProductDetail")
    public R<PmsBrand> brandProductDetail(Long brandId) {
        return R.ok(pmsBrandService.brandProductDetail(brandId));
    }

    //查询标签列表
    @ApiOperation("品牌商品列表标签")
    @PostMapping("/brandProductLabel")
    public ResponseEntity<Page<PmsLabel>> brandProductLabel(@RequestBody PmsProductDTO query, Pageable page){
        //根据名称查询商品信息
        List<PmsProductDTO> pmsProducts = pmsProductService.brandProductList(query, page);
        String labelIds = "";
        for (PmsProductDTO pmsProduct : pmsProducts) {
            if (!labelIds.isEmpty()) {
                labelIds += ","; // 添加分隔符
            }
            labelIds += pmsProduct.getLabelId();
        }
        Long[] longArray = Arrays.stream(labelIds.split(","))
                .map(String::trim)       // 去除空格
                .filter(s -> !s.isEmpty())
                .map(Long::valueOf)      // 转换为Long
                .toArray(Long[]::new);   // 转为Long数组
        List<PmsLabel> labelList = pmsLabelService.getLabelList(longArray);
        return ResponseEntity.ok(new PageImpl<>(labelList, page, labelList.size()));
    }


    @ApiOperation("新增品牌关注")
    @PostMapping("/addBrandAttention")
    public R<String> addBrandAttention(@RequestBody PmsBrandAttention pmsBrandAttention) {
        try {
            int data = brandAttentionService.insert(pmsBrandAttention);
            if (data == 0){
                return R.ok("删除失败");
            }
            return R.ok("删除成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @ApiOperation("删除品牌关注")
    @GetMapping("/removeBrand")
    public R<String> removeBrand(Long brandId) {
        UserInfo member = (UserInfo) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        try {
            int data = brandAttentionService.removeBrand(member.getId(), brandId);
            if (data == 0){
                return R.ok("删除失败");
            }
            return R.ok("删除成功");
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }


    //查询标签列表
    @ApiOperation("最近购买")
    @PostMapping("/recentlys")
    public ResponseEntity<Page<RecentlyBuyCVo>> recentlys(@RequestBody OrderItem query, Pageable page){
        List<RecentlyBuyCVo> list = pmsProductService.recentlys(query, page);
        return ResponseEntity.ok(new PageImpl<>(list, page, list.size()));
    }

    //查询商品参数配置
    @ApiOperation("查询商品参数配置")
    @GetMapping("/paramsJson")
    public R<List<Map<String,String>>> paramsJson(Long id){

        return R.ok(pmsProductService.paramsJson(id));
    }



}
